/**
 * 此类使用ormlite完成数据库创建等功能
 */

package com.yinhe.music.yhmusic.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;

import java.sql.SQLException;

abstract public class DbHelper extends OrmLiteSqliteOpenHelper {

    private final static String TAG = DbHelper.class.getSimpleName();
    private String dbName;

    public DbHelper(Context context, String dbName, int dbVersion) {
        super(context, dbName, null, dbVersion);
        this.dbName = dbName;

        Log.e(TAG, "DbHelper constructor");
    }

    public String getDbName() {
        return dbName;
    }

    private String dbOpenAccountAction;
    private String dbOpenAccountDbName;

    public void setDBOpenAccount(String action, String dbName) {
        this.dbOpenAccountAction = action;
        this.dbOpenAccountDbName = dbName;
    }

    public String getDbOpenAccountAction() {
        return dbOpenAccountAction;
    }

    public String getDbOpenAccountDbName() {
        return dbOpenAccountDbName;
    }

    @Override
    public void onCreate(SQLiteDatabase database,
                         ConnectionSource connectionSource) {

        logger.info("DbHelper onCreate, name = " + dbName);
        try {
            onDbCreate(database, connectionSource);
        } catch (SQLException e) {
            logger.error("DbHelper onCreate ERROR", e);
        }
    }


    protected abstract void onDbCreate(SQLiteDatabase database, ConnectionSource connectionSource) throws SQLException;

    @Override
    public void onUpgrade(SQLiteDatabase database,
                          ConnectionSource connectionSource, int oldVersion,
                          int newVersion) {
        logger.info("DbHelper onUpdate old " + oldVersion + " new " + newVersion);

        try {
            onDbUpgrade(database, connectionSource, oldVersion, newVersion);
        } catch (SQLException e) {
            logger.error("DbHelper onUpgrade ERROR", e);
        }
    }

    protected abstract void onDbUpgrade(SQLiteDatabase database,
                                        ConnectionSource connectionSource, int oldVersion,
                                        int newVersion) throws SQLException;

    @Override
    public void close() {
        super.close();
    }
}